package com.elitedatai.mchtest.manage.service.impl;

import com.elitedatai.mchtest.manage.model.dto.WorkspaceDTO;
import com.elitedatai.mchtest.manage.model.entity.WorkspaceEntity;
import com.elitedatai.mchtest.manage.repository.WorkSpaceRepository;
import com.elitedatai.mchtest.manage.service.IWorkSpaceService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 工作空间服务实现类
 */
@Service
@Transactional
public class WorkspaceServiceImpl implements IWorkSpaceService {

    /**
     * 工作空间数据访问对象
     */
    @Autowired
    private WorkSpaceRepository repository;

    /**
     * JSON对象映射器
     */
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 根据工作空间ID获取工作空间信息
     * @param workspaceId 工作空间ID
     * @return 工作空间DTO对象的可选包装
     */
    @Override
    public Optional<WorkspaceDTO> getWorkspaceByWorkspaceId(String workspaceId) {
        return Optional.ofNullable(entityConvertToDto(
                repository.findByWorkspaceId(workspaceId).orElse(null)));
    }

    /**
     * 根据绑定码获取工作空间信息
     * @param bindCode 绑定码
     * @return 工作空间DTO对象的可选包装
     */
    @Override
    public Optional<WorkspaceDTO> getWorkspaceNameByBindCode(String bindCode) {
        return Optional.ofNullable(entityConvertToDto(
                repository.findByBindCode(bindCode).orElse(null)));
    }

    /**
     * 将数据库实体对象转换为工作空间数据传输对象
     * @param entity 工作空间实体对象
     * @return 工作空间DTO对象
     */
    private WorkspaceDTO entityConvertToDto(WorkspaceEntity entity) {
        if (entity == null) {
            return null;
        }
        return WorkspaceDTO.builder()
                .id(entity.getId())
                .workspaceId(entity.getWorkspaceId())
                .platformName(entity.getPlatformName())
                .workspaceDesc(entity.getWorkspaceDesc())
                .workspaceName(entity.getWorkspaceName())
                .bindCode(entity.getBindCode())
                .build();
    }
}